package com.principle.other;

/**
 * @author 冯志立
 * @create 2019-10-15 13:28
 */
public class DependencyInvert {
    public static void main(String[] args) {
        //第一种方式
        ChangHong changHong = new ChangHong();
        OpenAndClose openAndClose = new OpenAndClose();
        openAndClose.openTv(changHong);
        //第二种方式
        OpenAndClose2 openAndClose2 = new OpenAndClose2(changHong);
        openAndClose2.open();
        //第三种方式
        OpenAndClose3 openAndClose3 = new OpenAndClose3();
        openAndClose3.setTv(changHong);
        openAndClose3.open();
    }
}

/**
 * 公共需要的类
 */
interface ITV {
    public void play(); //ITV接口
}

class ChangHong implements ITV {
    @Override
    public void play() {
        System.out.println("长虹电视机打开了");
    }
}

//依赖倒转的三种传递方式

/**
 * 1.接口传递方式
 */
interface IOpenAndClose {
    //开关的接口
    void openTv(ITV tv); //抽象方法用于接收接口
}
//实现接口
class OpenAndClose implements IOpenAndClose {
    @Override
    public void openTv(ITV tv) {
        tv.play();
    }
}

/**
 * 2.通过构造方法传递
 */
interface IOpenAndClose2 {
    void open();
}

class OpenAndClose2 implements IOpenAndClose2 {
    public ITV itv;

    public OpenAndClose2(ITV itv) {
        this.itv = itv;
    }

    @Override
    public void open() {
        itv.play();
    }
}

/**
 * 3.通过setter方式传递
 */
interface IOpenAndClose3 {
    void open();

    void setTv(ITV itv);
}

class OpenAndClose3 implements IOpenAndClose3 {
    private ITV itv;

    @Override
    public void open() {
        this.itv.play();
    }

    @Override
    public void setTv(ITV itv) {
        this.itv = itv;
    }
}

